<template>
  <div class="add-root">
    <el-dialog
      v-model="addDialogShowFlag"
      :title="createTitle ? '新增' : '编辑'"
      width="500"
    >
      <el-form v-model="userForm" label-position="right" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户名">
              <el-input
                v-model="userForm.userName"
                placeholder="请输入用户名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="性别">
              <el-select
                placeholder="全部"
                v-model="userForm.gender"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in genderList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirmClick(userForm)"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { add, updateUser } from '@/api'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'

const $emit = defineEmits(['reload'])
const addDialogShowFlag = ref(false)

const createTitle = ref(true)
const userForm = reactive({
  userId: null,
  userName: '',
  gender: null
})

const genderList = ref<any[]>([
  { value: 1, label: '男' },
  { value: 2, label: '女' }
])

const changeShowFlag = (userInfo?: any) => {
  addDialogShowFlag.value = true

  if (userInfo) {
    userForm.userName = userInfo.userName
    userForm.gender = userInfo.gender
    userForm.userId = userInfo.userId
    createTitle.value = false
  } else {
    userForm.userName = ''
    userForm.gender = null
  }
}

const handleConfirmClick = async (form: any) => {
  if (createTitle.value) {
    await add({ ...form })
    ElMessage.success('新增成功')
  } else {
    await updateUser({ ...form })
    ElMessage.success('更新成功')
  }

  addDialogShowFlag.value = false
  $emit('reload')
}

defineExpose({ changeShowFlag })
</script>

<style lang="scss" scoped>
.add-root {
  // background-color: #fff;
}
</style>
